package org.hzero.order.api.controller.v1;

import io.swagger.annotations.Api;
import org.hzero.boot.platform.code.builder.CodeRuleBuilder;
import org.hzero.core.util.Results;
import org.hzero.core.base.BaseController;
import org.hzero.order.app.service.SoHeaderService;
import org.hzero.order.config.SwaggerApiConfig;
import org.hzero.order.domain.entity.SoHeader;
import org.hzero.order.domain.vo.SoHeaderVO;
import org.hzero.order.domain.repository.SoHeaderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import io.choerodon.core.iam.ResourceLevel;
import io.choerodon.swagger.annotation.Permission;
import io.swagger.annotations.ApiOperation;

import java.util.List;


/**
 * @ Description   :  销售订单头管理 API
 * @ Author        :  xiong.yilin@hand-china.com
 * @ CreateDate    :  2019/8/8 10:29
 */
@Api(tags = SwaggerApiConfig.SOHEADER)
@RestController("soHeaderController.v1")
@RequestMapping("/v1/{organizationId}/so-headers")
public class SoHeaderController extends BaseController {

    @Autowired
    private SoHeaderRepository soHeaderRepository;
    @Autowired
    private CodeRuleBuilder codeRuleBuilder;
    @Autowired
    private SoHeaderService soHeaderService;

    @ApiOperation(value = "销售订单头列表")
    @Permission(level = ResourceLevel.ORGANIZATION)
    @GetMapping
    public ResponseEntity<List<SoHeaderVO>> list
            (@PathVariable("organizationId") Long tenantId, SoHeader soHeader) {
        List<SoHeaderVO> soHeaders = soHeaderService.selectByConditions(soHeader);
        return Results.success(soHeaders);
    }

    @ApiOperation(value = "创建销售订单")
    @Permission(level = ResourceLevel.ORGANIZATION)
    @PostMapping
    public ResponseEntity<SoHeaderVO> create
            (@PathVariable("organizationId") Long tenantId, @RequestBody SoHeaderVO soHeaderVo) {
        // 简单数据校验
        this.validObject(soHeaderVo);
        //按照编码规则生成订单号
        String orderNumber = codeRuleBuilder.generateCode(tenantId, "HZERO.25590.ORDER.NUMBER", "GLOBAL", "GLOBAL", null);
        // 创建订单
        soHeaderVo.setOrderNumber(orderNumber);
        return Results.success(soHeaderService.create(soHeaderVo));
    }

    @ApiOperation(value = "修改销售订单头")
    @Permission(level = ResourceLevel.ORGANIZATION)
    @PutMapping
    public ResponseEntity<SoHeader> update
            (@PathVariable("organizationId") Long tenantId, @RequestBody SoHeader soHeader) {
        // 简单数据校验
        this.validObject(soHeader);
        soHeaderService.updateById(soHeader);
        return Results.success(soHeader);
    }


}
